//
//  HRComposeViewController.swift
//  microBlog
//
//  Created by HR_W on 16/5/28.
//  Copyright © 2016年 admin. All rights reserved.
//

import UIKit
import SVProgressHUD

class HRComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
     
        setupUI()
        registerNotification()
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        if pictureSelector.images.count == 0 {
            
            textView.becomeFirstResponder()
        }
    }
    
    //注册通知
    private func registerNotification() {
    
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyBoradChange(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
    
    }
    
    //键盘将要改变frame toolBar需要做动画效果
    @objc private func keyBoradChange(n: NSNotification){
    
        print(n)
        //获取键盘显示或者隐藏的动画时间
        let time_t = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue
        //结构体中能够直接存放在字典中? 需要转化为NSValue
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue()
        //获取键盘的frame
        let offsetY = -ScreenHeight + rect!.origin.y
        
        UIView.animateWithDuration(time_t!) { 
            
            self.toolBar.snp_updateConstraints(closure: { (make) in
                make.bottom.equalTo(offsetY)
            })
            
            self.view.layoutIfNeeded()
        }
        
    }
    
    @objc private func close() {
        
    dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func send(){
        
       print("发送")
        HMNetworkTools.sharedTools.sendStatus(textView.text,images: pictureSelector.images) { (responseObject, error) in
            if error != nil{
            
            SVProgressHUD.showErrorWithStatus("发布微博失败")
            }
           
            SVProgressHUD.showSuccessWithStatus("发布微博成功")
        }
        
    }
    @objc private func selectPicture(){
    
        print("选中图片")
        
        pictureSelector.view.snp_updateConstraints { (make) in
            make.height.equalTo(ScreenHeight / 3 * 2)
        }
    }
    @objc private func selectEmoticon(){
    
        print("选中表情")
    
    }
    
 
    private lazy var rightBarButtonItem: UIBarButtonItem = {
            let btn = UIButton()
        btn.setTitle("发送", forState: .Normal)
        btn.addTarget(self, action: #selector(send), forControlEvents: .TouchUpInside)
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Disabled)
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        btn.frame = CGRect(x: 0, y: 0, width: 45, height: 30)

        let barButtonItem = UIBarButtonItem(customView: btn)
        
        return barButtonItem
    }()
    
    private lazy var textView: UITextView = {
        let tv = UITextView()
        tv.backgroundColor = UIColor(white: 0.8, alpha: 1)
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        tv.keyboardDismissMode = .OnDrag
        tv.alwaysBounceVertical = true
        tv.delegate = self
        return tv
    }()
    
    private lazy var placeHolderLabel: UILabel = UILabel(titie: "输入文本文字", font: 18, textColor: UIColor.darkGrayColor())
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    private lazy var pictureSelector: HRPictureSelectorController = HRPictureSelectorController()
    //移除通知
    deinit{
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

extension HRComposeViewController {

    private func setupUI() {
    
        setNavBar()
        
        setTextView()
        
        setToolBar()
        setSelectorVc()
    }
    
    
    private func setSelectorVc() {
        //添加子视图控制器
        self.addChildViewController(pictureSelector)
        //使用控制器的view
        self.view.addSubview(pictureSelector.view)
        //将toolBar移动带最前面
        self.view.bringSubviewToFront(toolBar)
        
        pictureSelector.view.snp_makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(0)
        }

    }
    
    //设置底部工具条
    private func setToolBar() {
    
        self.view.addSubview(toolBar)
        
        //设置约束
        toolBar.snp_makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            //工具条有默认高度
        }
        var items = [UIBarButtonItem]()
        //操作数据 添加UIBarButtonItem
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
                            ["imageName": "compose_mentionbutton_background","actionName": "selectPicture"],
                            ["imageName": "compose_trendbutton_background","actionName": "selectPicture"],
                            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
                            ["imageName": "compose_add_background","actionName": "selectPicture"]]
        for item in itemSettings{
        
            let imageName = item["imageName"]
            let action = item["actionName"]!
            let item = UIBarButtonItem(imageName: imageName, target: self, action: Selector(action), title: nil)
            items.append(item)
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            
            items.append(space)
  
        }
        items.removeLast()
        toolBar.items = items
        
    }
    
    
    private func setTextView(){
        
        self.view.addSubview(textView)
        //设置约束
        textView.snp_makeConstraints { (make) in
            make.top.left.right.equalTo(self.view)
            //设置高度
            make.height.equalTo(ScreenHeight / 3)
        }
        
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) in
            make.left.equalTo(textView.snp_left).offset(5)
            make.top.equalTo(textView.snp_top).offset(8)
        }
        
    
    }

    private func setNavBar() {
    
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(target: self, action: #selector(HRComposeViewController.close), title: "关闭")
    
       navigationItem.rightBarButtonItem = rightBarButtonItem
        
        navigationItem.rightBarButtonItem?.enabled = false
    
        let myView = UIView(frame: CGRect(x: 0, y: 0, width: 220, height: 40))
        
         let titleLabel = UILabel(titie: "发送微博", font: 16, textColor: UIColor.darkGrayColor())
      
        let nameLabel = UILabel(titie: HRUserAccountViewModel.shareAccountViewModel.userAccount?.name ?? "", font: 13, textColor: UIColor.lightGrayColor())
        
        myView.addSubview(titleLabel)
        myView.addSubview(nameLabel)
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(myView.snp_centerX)
            make.top.equalTo(myView.snp_top)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(myView.snp_centerX)
            make.bottom.equalTo(myView.snp_bottom)
        }
        //赋值的操作
        navigationItem.titleView = myView
        
    }
    
    

}


extension HRComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        
        placeHolderLabel.hidden = textView.hasText()
        
        rightBarButtonItem.enabled = textView.hasText()
        
    }

}
